package com.axx.android.profile.like;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.activity.UserAdapter;
import com.axx.android.letter.activity.LetterDetailActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class LikeActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    Button mBtnBack;
    @Bind(R.id.layout_toolbar)
    RelativeLayout mLayoutToolbar;
    @Bind(R.id.vs_error)
    ViewStub mVsError;
    @Bind(R.id.rv_list)
    RecyclerView mRvList;
    @Bind(R.id.refresh_view)
    SJRefreshView mRefreshView;
    @Bind(R.id.activity_like)
    LinearLayout mActivityLike;
    private int curPage = 1;
    private int pageSize = 15;

    private List<LikeLetter.CollectionListBean> list = new ArrayList<>();
    private LikeLetterAdapter adapter;
    private View viewError;
    private LikeLetter.CollectionListBean curModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_like;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        fetchLetter();
        initAdapter();
        refresh();
        mRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchLetter();
            }
        });
    }

    private void fetchLetter() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("nowpage", curPage + "");
        hashMap.put("pagenum", pageSize + "");
        hashMap.put("userId", LetterApp.authUser.getId());
        HttpUtils.post(Constants.Url.Profile.PROFILE_LIKE, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<LikeLetter> likeLetterBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<LikeLetter>>() {
                    });
                    if (likeLetterBaseModel.isSuccess()) {
                        showSuccess(likeLetterBaseModel.data.getCollectionList());
                    } else {
                        showToast(likeLetterBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mRefreshView.setRefreshing(false);
                    showErrorView();
                }
            }

            @Override
            public void onError() {
                mRefreshView.setRefreshing(false);
                showErrorView();
            }
        });
    }

    private void showSuccess(List<LikeLetter.CollectionListBean> collectionList) {
        mRefreshView.setRefreshing(false);
        if (viewError != null) {
            viewError.setVisibility(View.GONE);
        }
        if (curPage == 1) {
            adapter.setNewData(collectionList);
            adapter.disableLoadMoreIfNotFullPage(mRvList);
        } else {
            int loadCount = collectionList.size();
            adapter.addData(collectionList);
            if (loadCount < 8) {
                adapter.loadMoreEnd();
            } else {
                adapter.loadMoreComplete();
            }
        }

    }


    private void showErrorView() {
        if (viewError == null) {
            viewError = mVsError.inflate();
            viewError.findViewById(R.id.btn_retry).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    viewError.setVisibility(View.GONE);
                    refresh();
                }
            });
        } else {
            viewError.setVisibility(View.VISIBLE);
        }
    }

    private void refresh() {
        mRefreshView.post(new Runnable() {
            @Override
            public void run() {
                mRefreshView.setRefreshing(true);
                fetchLetter();
            }
        });
    }

    private void initAdapter() {
        adapter = new LikeLetterAdapter(R.layout.view_item_like_letter, list);
        mRvList.setAdapter(adapter);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        adapter.setLoadMoreView(new SimpleLoadMoreView());
        adapter.setEmptyView(R.layout.view_default_emtpy, mRvList);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchLetter();
            }
        }, mRvList);
        mRvList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).build());
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LikeLetter.CollectionListBean collectionListBean = (LikeLetter.CollectionListBean) adapter.getData().get(position);
                Intent intent = new Intent(LikeActivity.this, LetterDetailActivity.class);
                intent.putExtra("from", "detail");
                intent.putExtra("id", collectionListBean.getId());
                startActivity(intent);
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                curModel = (LikeLetter.CollectionListBean) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_like:
                        like();
                        break;
                    case R.id.iv_up:
                        up();
                        break;
                }
            }
        });
    }


    private void up() {
        HttpUtils.post(Constants.Url.Letter.LETTER_UP, getPostData(), new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Integer> stringBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Integer>>() {
                    });
                    if (stringBaseModel.isSuccess()) {
                        if (stringBaseModel.data == 1) {
                            curModel.setGood(curModel.getGood() + 1);
                        } else {
                            curModel.setGood(curModel.getGood() - 1);
                        }
                        curModel.setGoodStatus(stringBaseModel.data);
                        adapter.notifyDataSetChanged();
                    } else {
                        showToast(stringBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }

    private void like() {
        HttpUtils.post(Constants.Url.Letter.LETTER_LIKE, getPostData(), new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Integer> stringBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Integer>>() {
                    });
                    if (stringBaseModel.isSuccess()) {
                        if (stringBaseModel.data == 1) {
                            showToast("收藏成功");
                        } else {
                            showToast("取消收藏成功");
                        }
                        curModel.setCollectionStatus(stringBaseModel.data);
                        adapter.notifyDataSetChanged();
                    } else {
                        showToast(stringBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }

    private HashMap<String, String> getPostData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("letterId", curModel.getId());
        map.put("userId", LetterApp.authUser.getId());
        return map;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
